import * as Cesium from 'cesium';
import * as Libora from '../../public/libora/index.js'
import { HelperLib } from '../mesh/HelperLib.js'
import { MyPrimitive } from '../primitive/MyPrimitive.js';

(window).Cesium = Cesium;
// (window).Libora = Libora;

export default class Demo {
  constructor() {
    const viewer = Libora.getViewer({
      // imageryProvider: false,
      // globe: false,
    });

    window.viewer = viewer;
    viewer.scene.skyBox.show = false
    // Libora.setCameraInput(viewer);
    // Libora.addGaode2(viewer);

    let info = {};
    info.lon = 116.39713829145771;
    info.lat = 39.91941703971191;

    this.viewer = viewer;
    this._isStart = null;

    this._getRealPositions = this._getRealPositions.bind(this);
    this._success = this._success.bind(this);
    this._error = this._error.bind(this);
    this.toggle = this.toggle.bind(this);
    document.querySelector(".slider").addEventListener("click", this.toggle)

    this._realPositions = [];

    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(info.lon, info.lat, 10000000.0),
      duration: 0,
    });

    this._markerEntity = viewer.entities.add({
      position: new Cesium.Cartesian3(),
      billboard: {
        image: '../../public/images/marker.png',
        scale: 0.5,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      }
    });

    viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(this._getRealPositions, false),
        width: 2,
        material: Cesium.Color.RED,
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 800 * 10000)
      }
    });
  }

  _getRealPositions() {
    return this._realPositions
  }

  toggle() {

    if (this._isStart === null) {
      console.error("start...");
      this._isStart = true;
      this._startTracking();
    } else {
      this._isStart = !this._isStart;
    }
  }

  _error(err) {
    console.error(`${err.code} - ${err.message}`);
  }

  _success(info) {
    const { latitude, longitude } = info.coords;
    const timestamp = new Date(Date.now()).toISOString();

    const gpsInfo = {
      latitude,
      longitude,
      timestamp
    }
    // accuracy,定位精准度（单位：米）,altitudeAccuracy 高度
    console.error(info);

    // console.log('success', gpsInfo);
    this._updateMap(gpsInfo);
  }

  _pushPosition(arr, position) {
    if (arr.length === 0) {
      arr.push(position);
      return;
    }

    const distance = Cesium.Cartesian3.distance(arr[arr.length - 1], position);
    console.log('distance', distance);
    if (distance < 0.5) {
      return;
    } else {
      arr.push(position);
    }
  }

  _startTracking() {

   const onComplete = (data)=> {
      // data是具体的定位信息
      const wgsPoint = [data.coords.longitude, data.coords.latitude]//Libora.CoordTransform.GCJ02ToWGS84(data.position.lng, data.position.lat)

      if(data.coords.accuracy>500) return;
      viewer.scene.requestRender()
      console.error(wgsPoint);
      const realPosition = Cesium.Cartesian3.fromDegrees(wgsPoint[0], wgsPoint[1]);
      this._markerEntity.position = realPosition;
      this._pushPosition(this._realPositions, realPosition);

      if (!this._isFirst) {
        this._isFirst = true;
        this.viewer.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(wgsPoint[0], wgsPoint[1], 10000.0),
          duration: 0,
        });
      }
      setTimeout(() => {
        this._startTracking()
      }, 2000);
    }

    navigator.geolocation.getCurrentPosition(onComplete);

    // AMap.plugin('AMap.Geolocation', function () {
    //   var geolocation = new AMap.Geolocation({
    //     enableHighAccuracy: false, // 是否使用高精度定位，默认：true
    //     timeout: 10000, // 设置定位超时时间，默认：无穷大
    //     convert: false // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
    //   })

    //   geolocation.getCurrentPosition()
      // AMap.event.addListener(geolocation, 'complete', onComplete)
      // AMap.event.addListener(geolocation, 'error', onError)



    //   function onError(data) {
    //     // 定位出错
    //     console.error(data);
    //   }
    // })
  }
}
